<template>
  <a-table
    :columns="columns"
    :data-source="addedMembers"
    :pagination="false"
    :scroll="{ y: 150 }"
  >
    <div slot="name" slot-scope="text, _, index">
      <a-select
        placeholder="请搜索"
        show-search
        size="small"
        class="select"
        @search="handleSearch"
        @change="(value) => changeMemberName(index, value)"
      >
        <a-icon
          slot="suffixIcon"
          type="search"
          :style="{ 'font-size': '18px', margin: '-3px -4px' }"
        />
        <a-select-option
          v-for="option in userList"
          :key="option.id"
          :value="option.name"
        >
          {{ option.name }}
        </a-select-option>
      </a-select>
    </div>
    <div slot="role" slot-scope="text, _, index">
      <a-select
        placeholder="请选择"
        class="select"
        size="small"
        default-value="协作者"
        @change="(value) => changeMemberRole(index, value)"
      >
        <a-select-option value="协作者">协作者</a-select-option>
        <!--        <a-select-option value="游客">游客</a-select-option> 暂时去掉游客角色-->
      </a-select>
    </div>
    <a-icon
      slot="delete"
      slot-scope="_, __, index"
      type="minus-circle"
      @click="() => deleteRow(index)"
    />
    <div slot="footer" class="add-member-page-footer">
      <a-button class="btn-add" type="link" style="padding: 0;" @click="addRow"
        ><a-icon type="plus" />添加</a-button
      >
    </div>
  </a-table>
</template>

<script lang="ts">
/**
 * page of adding members
 * @author Huihua Lu
 */
import { Component, Vue, Emit } from 'vue-property-decorator'
import ProjectStore from '@/store/modules/project'
import UserStore from '@/store/modules/user'
import { debounce } from 'lodash'
import { queryInfoByName } from '@/api/user'

interface MemberOption {
  id: number | null
  name: string | null
  role: string | null
}

@Component({})
export default class AddMemberPage extends Vue {
  private columns = [
    {
      title: '成员',
      dataIndex: 'name',
      key: 'name',
      scopedSlots: { customRender: 'name' },
      ellipsis: true,
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      scopedSlots: { customRender: 'role' },
    },
    {
      dataIndex: 'delete',
      key: 'delete',
      scopedSlots: { customRender: 'delete' },
      width: 80,
    },
  ]

  // 添加的成员列表，用空成员表示待填项
  private addedMembers: Array<MemberOption> = [
    {
      id: null,
      name: null,
      role: '协作者',
    },
  ]

  // 所有可以选择的成员名单
  private allMembers: Array<any> = []

  public async created(): Promise<void> {
    // < 弃用  hou jinhui 20210118>
    // await ProjectStore.getAllProjectMembers()
    // this.allMembers = ProjectStore.projectMembers.map(m => {
    //   return {
    //     id: m.id,
    //     name: m.name
    //   }
    // })
  }

  // 从所有可选的成员名单中过滤已添加的成员和自己   < 弃用  hou jinhui 20210118>
  public get memberOptions(): Array<any> {
    const addedNames: Set<string> = new Set()
    ProjectStore.projectAuth.forEach((m) => {
      addedNames.add(m.userName)
    })
    // 去掉自己
    addedNames.add(UserStore.currentUser ? UserStore.currentUser.name : '')
    return this.allMembers.filter((m) => !addedNames.has(m.name))
  }

  // ------ replace ----
  // 模糊搜索 用户
  public userList: any[] = []
  // 关键字 模糊搜索用户
  public handleSearch(searchKey: string) {
    if (searchKey.trim().length >= 2) {
      this.queryUsersByName(searchKey.trim())
    }
  }
  // 防抖
  private queryUsersByName = debounce(
    (searchKey: string) => this._handleSearch(searchKey),
    100
  )
  public _handleSearch(searchKey: string) {
    const parameters = {
      name: searchKey,
    }
    queryInfoByName({ data: parameters })?.then((response: any) => {
      if (response.data.code === 100) {
        // 去掉自己
        const filterUsers = response.data.result.filter(
          (user: any) => user.id !== UserStore.currentUser?.id
        )
        this.userList = filterUsers
        this.allMembers = filterUsers // 保持原代码 （changeMemberName 中 根据 name 查 id）
      }
    })
  }
  //  -- replace end

  /* 添加成员 */
  @Emit('changeMemberList')
  public changeMemberName(index: number, name: string) {
    this.addedMembers[index].name = name
    const i = this.allMembers.map((p) => p.name).indexOf(name)
    this.addedMembers[index].id = this.allMembers[i].id
    return this.addedMembers
  }

  @Emit('changeMemberList')
  public changeMemberRole(index: number, role: string) {
    this.addedMembers[index].role = role
    return this.addedMembers
  }

  @Emit('changeMemberList')
  public addRow() {
    this.addedMembers.push({
      id: null,
      name: null,
      role: '协作者',
    })
    return this.addedMembers
  }

  @Emit('changeMemberList')
  public deleteRow(index: number) {
    if (this.addedMembers.length > 1) {
      this.addedMembers.splice(index, 1)
    }
    return this.addedMembers
  }
}
</script>

<style lang="less">
.select {
  height: 24px;
  width: 134px;
}

ul li:hover {
  color: #5760e6;
}

/* 修改底部footer样式 */
.ant-table-footer {
  padding: 0 16px;
}

/* 禁用动画 */
.ant-select-open .ant-select-arrow-icon svg {
  transform: none;
}

.add-member-page-footer {
  .btn-add {
    display: block;
    margin-top: 4px;
    width: 100%;

    span {
      margin-left: 4px !important;
    }
  }
}
</style>
